//
//  SimDatePicker.h
//
//  Created by XubinLiu.
//

#import "SimDatePicker.h"
#import "SimCommonTool.h"
#import "SimDefine.h"
#import "UIView+SimAdditions.h"


#define kSimDatePickerMonthCount 12
#define kSimDatePickerHourCount 24
#define kSimDatePickerMinuteCount 60

#ifndef CustomSimDatePickerSetting

#define kSimDatePickerDisableColor           HEXRGBCOLOR(0xe6e6e6)
#define kSimDatePickerHighlightedColor       [UIColor blackColor]
#define kSimDatePickerItemFont               [UIFont systemFontOfSize:18.0]
#define kSimDatePickerItemTintColor          HEXRGBCOLOR(0x44cdfc)

#endif


@interface SimDatePicker ()
{
    UIPickerView *_myPickerView;
    UIToolbar *_toolbar;
    
    //日期存储数组
    NSMutableDictionary *_lbDataDict;
    NSMutableDictionary *_lbDataSelectRowDict;
    
    NSDate *_minLimitDate;
    NSDate *_maxLimitDate;
    NSDictionary *_minDateValues;
    NSDictionary *_maxDateValues;
}

@end

@implementation SimDatePicker

- (id)initWithDateLables:(NSArray *)dateLbs minDate:(NSDate *)minDate maxDate:(NSDate *)maxDate
{
    self = [self initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 10)];
    if (self) {
        _dateLables = dateLbs;
        self.minLimitDate = minDate ? : [NSDate date];
        NSString *yearString = [SimCommonTool stringFromDate:_minLimitDate format:@"yyyy"];
        NSInteger minYeaer = [yearString integerValue];

        if (maxDate) {
            self.maxLimitDate = maxDate;
            yearString = [SimCommonTool stringFromDate:_maxLimitDate format:@"yyyy"];
        }
        else{
            self.maxLimitDate = [SimCommonTool dateFromString:[NSString stringWithFormat:@"%ld", (long)minYeaer+50] format:@"yyyy"];
        }
        
        CGFloat totalWidth = 0;
        for (int i=0; i < _dateLables.count; i++) {
            CGFloat width = [self pickerView:_myPickerView widthForComponent:i];
            totalWidth += width;
            UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, width, 20)];
            label.text = [self nameForLb:[_dateLables[i] integerValue]];
            label.textAlignment = NSTextAlignmentRight;
            label.font = [UIFont systemFontOfSize:18];
            label.textColor = kSimDatePickerHighlightedColor;
            label.backgroundColor = [UIColor clearColor];
            label.centerY = _myPickerView.centerY;
            label.tag = 10+i;
            [self addSubview:label];
        }
        
        CGFloat left = (self.width-totalWidth)/2;
        CGFloat gap = -5;
        for (int i = 0; i < _dateLables.count; i++) {
            UIView *view = [self viewWithTag:10+i];
            view.left = left+gap;
            left += view.width;
            gap += ABOVE_IOS7 ? 4 : 2;
        }
    }
    
    return self;
}

- (void)setMinLimitDate:(NSDate *)minLimitDate
{
    _minLimitDate = minLimitDate;
    _minDateValues = [self dateValueDict:_minLimitDate];
    if (_maxDateValues) {
        [self updateYearCount];
    }
}

- (void)setMaxLimitDate:(NSDate *)maxLimitDate
{
    _maxLimitDate = maxLimitDate;
    _maxDateValues = [self dateValueDict:_maxLimitDate];
    if (_minLimitDate) {
        [self updateYearCount];
    }
}

//进行初始化
- (void)drawRect:(CGRect)rect
{
    
}

- (void)dealloc
{
    NSLog(@"dealloc");
}

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor whiteColor];
        
        UIToolbar *dateToolBar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, self.width, 44)];
       
        UIBarButtonItem *space = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
        UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(doCancel)];
        UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(doDone)];
        if (ABOVE_IOS7) {
            UILabel *leftLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 1, 44.0f)];
            leftLabel.backgroundColor = [UIColor clearColor];
            UIBarButtonItem *leftSpace = [[UIBarButtonItem alloc] initWithCustomView:leftLabel];
            
            UILabel *rightLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 1, 44.0f)];
            rightLabel.backgroundColor = [UIColor clearColor];
            UIBarButtonItem *rightSpace = [[UIBarButtonItem alloc] initWithCustomView:rightLabel];
            
            dateToolBar.items = @[leftSpace, leftItem, space, rightItem, rightSpace];
        }else{
            dateToolBar.items = @[leftItem, space, rightItem];
        }
        [leftItem setTintColor:kSimDatePickerItemTintColor];
        [rightItem setTintColor:kSimDatePickerItemTintColor];
        
        NSDictionary* textAttributes = @{NSFontAttributeName:kSimDatePickerItemFont,
                                         NSForegroundColorAttributeName:kSimDatePickerItemTintColor};
        [leftItem setTitleTextAttributes:textAttributes forState:UIControlStateNormal];
        [rightItem setTitleTextAttributes:textAttributes forState:UIControlStateNormal];
        [self addSubview:dateToolBar];
        
        _myPickerView = [[UIPickerView alloc]initWithFrame:CGRectMake(0, dateToolBar.bottom, self.width, 216.0)];
        _myPickerView.showsSelectionIndicator = YES;
        _myPickerView.backgroundColor = [UIColor clearColor];
        _myPickerView.delegate = self;
        _myPickerView.dataSource = self;
        [self addSubview:_myPickerView];
        
        self.height = _myPickerView.height + dateToolBar.height;
        
      
        
        NSMutableArray *monthArray  = [NSMutableArray array];
        NSMutableArray *hourArray   = [NSMutableArray array];
        NSMutableArray *minuteArray = [NSMutableArray array];
        for (int i=0; i<kSimDatePickerMinuteCount; i++) {
            NSString *num = [NSString stringWithFormat:@"%02d",i];
            [minuteArray addObject:num];
            if (0<i && i<=kSimDatePickerMonthCount)
                [monthArray addObject:num];
            if (i<kSimDatePickerHourCount)
                [hourArray addObject:num];
        }
        
        
        _lbDataSelectRowDict = [NSMutableDictionary dictionary];
        _lbDataDict = [NSMutableDictionary dictionary];
        _lbDataDict[@(SDL_Month)] = monthArray;
        _lbDataDict[@(SDL_Hour)] = hourArray;
        _lbDataDict[@(SDL_Minute)] = minuteArray;
    }
    return self;
}



- (void)setScrollToDate:(NSDate *)date
{
    _scrollToDate = date;
    NSArray *indexArray = [self dateIndexes:date];
    for (int i=0; i<indexArray.count; i++) {
        NSInteger row = [indexArray[i] integerValue];
        _lbDataSelectRowDict[_dateLables[i]] = @(row);
    }
    [self updateDayCount];
    [self didSelectDate];
}

static NSDateFormatter *formatter = nil;
- (NSDictionary *)dateValueDict:(NSDate *)date
{
    if (formatter == nil) {
        formatter = [[NSDateFormatter alloc] init];
        [formatter setDateFormat:@"yyyyMMddHHmm"];
    }
    NSString *dateString = [formatter stringFromDate:date];
    NSMutableDictionary *valueDict = [NSMutableDictionary dictionary];
    valueDict[@(SDL_Year)] = [dateString substringWithRange:NSMakeRange(0, 4)];
    valueDict[@(SDL_Month)] = [dateString substringWithRange:NSMakeRange(4, 2)];
    valueDict[@(SDL_Day)] = [dateString substringWithRange:NSMakeRange(6, 2)];
    valueDict[@(SDL_Hour)] = [dateString substringWithRange:NSMakeRange(8, 2)];
    valueDict[@(SDL_Minute)] = [dateString substringWithRange:NSMakeRange(10, 2)];
    return valueDict;
}

- (NSDate *)dateFromSelectedRow
{
    if (formatter == nil) {
        formatter = [[NSDateFormatter alloc] init];
        [formatter setDateFormat:@"yyyyMMddHHmm"];
    }

    NSString *dateStr = [NSString stringWithFormat:@"%@%@%@%@%@",
                         [self valueForLb:SDL_Year],
                         [self valueForLb:SDL_Month],
                         [self valueForLb:SDL_Day],
                         [self valueForLb:SDL_Hour],
                         [self valueForLb:SDL_Minute]];
    return [formatter dateFromString:dateStr];
}

//获取当前时间解析及位置
- (NSArray *)dateIndexes:(NSDate *)date
{
    if (date == nil) {
        date = [NSDate date];
    }
    
    NSMutableArray *indexes = [NSMutableArray array];
    NSDictionary *valueDicts = [self dateValueDict:date];
    NSNumber *value = nil;
    SimDateLabel label = 0;
    for (NSNumber *dateLb in _dateLables) {
        label = [dateLb integerValue];
        if (label == SDL_Year) {
            value = @([valueDicts[dateLb] integerValue] - [_minDateValues[@(SDL_Year)] integerValue]);
        }
        else if(label == SDL_Month || label == SDL_Day) {
            value = @([valueDicts[dateLb] integerValue] - 1);
        }
        else{
            value = @([valueDicts[dateLb] integerValue]);
        }
        
        [indexes addObject:value];
    }

    return indexes;
}

- (NSString *)nameForLb:(SimDateLabel)lb
{
    switch (lb) {
        case SDL_Year:
            return @"年";
        case SDL_Month:
            return @"月";
        case SDL_Day:
            return @"日";
        case SDL_Hour:
            return @"时";
        case SDL_Minute:
            return @"分";
        default:
            return @"";
    }
}

- (NSNumber *)valueForLb:(SimDateLabel)lb
{
    NSInteger selectedIndex = [_lbDataSelectRowDict[@(lb)] integerValue];
    return _lbDataDict[@(lb)][selectedIndex];
}

- (BOOL)canSelectForPickerView:(UIPickerView *)pickerView row:(NSInteger)row component:(NSInteger)component
{
    NSNumber *lb = _dateLables[component];
    NSInteger curValue = [_lbDataDict[lb][row] integerValue];
    NSInteger minYear = [_minDateValues[@(SDL_Year)] integerValue];
    if ([lb integerValue] == SDL_Year) {
        NSInteger maxYear = [_maxDateValues[@(SDL_Year)] integerValue];
        if (curValue < minYear || curValue > maxYear) {
            return NO;
        }
    }
    
    NSInteger selectedYear = [[self valueForLb:SDL_Year] integerValue];
    if (minYear == selectedYear) {
        NSInteger minMonth = [_minDateValues[@(SDL_Month)] integerValue];
        if ([lb integerValue] == SDL_Month){
            if (curValue < minMonth) {
                return NO;
            }
        }
        
        NSInteger selectedMonth = [[self valueForLb:SDL_Month] integerValue];;
        if (selectedMonth == minMonth) {
            NSInteger minDay = [_minDateValues[@(SDL_Day)] integerValue];
            if ([lb integerValue] == SDL_Day){
                if (curValue < minDay) {
                    return NO;
                }
            }
            
            NSInteger selectedDay = [[self valueForLb:SDL_Day] integerValue];;
            if (selectedDay == minDay) {
                NSInteger minHour = [_minDateValues[@(SDL_Hour)] integerValue];
                if ([lb integerValue] == SDL_Hour){
                    if (curValue < minHour) {
                        return NO;
                    }
                }
                
                NSInteger selectedHour = [[self valueForLb:SDL_Hour] integerValue];;
                if (selectedHour == minHour) {
                    NSInteger minMinute = [_minDateValues[@(SDL_Minute)] integerValue];
                    if ([lb integerValue] == SDL_Minute){
                        if (curValue < minMinute) {
                            return NO;
                        }
                    }
                }
            }
        }
    }
    
    return YES;
}

#pragma mark - UIPickerViewDataSource
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return [_dateLables count];
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    return [_lbDataDict[_dateLables[component]] count];
}

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
{
    UILabel *customLabel = (UILabel *)view;
    if (!customLabel) {
        customLabel = [[UILabel alloc] init];
        customLabel.textAlignment = NSTextAlignmentCenter;
        [customLabel setFont:[UIFont systemFontOfSize:18]];
    }
    
    NSNumber *lb = _dateLables[component];
    BOOL canSelected = [self canSelectForPickerView:pickerView row:row component:component];
    customLabel.text = [NSString stringWithFormat:@"%@", _lbDataDict[lb][row]];
    customLabel.textColor = canSelected ? kSimDatePickerHighlightedColor : kSimDatePickerDisableColor;
    return customLabel;
}

#pragma mark - UIPickerViewDelegate
- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component
{
    SimDateLabel lb = [_dateLables[component] integerValue];
    if (lb == SDL_Year) {
        return 80;
    }
    else{
        return 60;
    }
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    _lbDataSelectRowDict[_dateLables[component]] = @(row);
    
    SimDateLabel lb = [_dateLables[component] integerValue];
    if (lb == SDL_Year || lb == SDL_Month) {
        [self updateDayCount];
        
        
    }
    [pickerView reloadAllComponents];
    
    
    NSDate *date = [self dateFromSelectedRow];
    if ([date compare:_minLimitDate] == NSOrderedAscending) {
        NSArray *array = [self dateIndexes:_minLimitDate];
        for (int i=0; i<array.count; i++) {
            NSInteger row = [array[i] integerValue];
            [pickerView selectRow:row inComponent:i animated:YES];
            _lbDataSelectRowDict[_dateLables[i]] = @(row);
        }
    }else if ([date compare:_maxLimitDate] == NSOrderedDescending){
        NSArray *array = [self dateIndexes:_maxLimitDate];
        for (int i=0; i<array.count; i++) {
            NSInteger row = [array[i] integerValue];
            [pickerView selectRow:row inComponent:i animated:YES];
            _lbDataSelectRowDict[_dateLables[i]] = @(row);
        }
    }
    
    [self didSelectDate];
}

#pragma mark - 数据处理
//通过日期求星期
//- (NSString*)getWeekDayWithYear:(NSString*)year month:(NSString*)month day:(NSString*)day
//{
//    NSInteger yearInt   = [year integerValue];
//    NSInteger monthInt  = [month integerValue];
//    NSInteger dayInt    = [day integerValue];
//    int c = 20;//世纪
//    int y = (int)yearInt -1;//年
//    int d = (int)dayInt;
//    int m = (int)monthInt;
//    int w =(y+(y/4)+(c/4)-2*c+(26*(m+1)/10)+d-1)%7;
//    NSString *weekDay = @"";
//    switch (w) {
//        case 0: weekDay = @"周日";    break;
//        case 1: weekDay = @"周一";    break;
//        case 2: weekDay = @"周二";    break;
//        case 3: weekDay = @"周三";    break;
//        case 4: weekDay = @"周四";    break;
//        case 5: weekDay = @"周五";    break;
//        case 6: weekDay = @"周六";    break;
//        default:break;
//    }
//    return weekDay;
//}

//通过年月求每月天数
- (NSInteger)updateDayCount
{
    if (!_lbDataSelectRowDict[@(SDL_Year)] || !_lbDataSelectRowDict[@(SDL_Month)]) {
        return 0;
    }
    
    NSInteger index = [_lbDataSelectRowDict[@(SDL_Year)] integerValue];
    NSInteger year  = [_lbDataDict[@(SDL_Year)][index] integerValue];
    
    index = [_lbDataSelectRowDict[@(SDL_Month)] integerValue];
    NSInteger month = [_lbDataDict[@(SDL_Month)][index] integerValue];
   
    NSInteger dayCount = 31;
    switch (month) {
        case 4:
        case 6:
        case 9:
        case 11:
            dayCount = 30;
            break;
        case 2:{
            BOOL isrunNian = (year%4==0 && year%100!=0)||(year%400==0);
            if (isrunNian) {
                dayCount = 29;
            }else{
                dayCount = 28;
            }
            
        }
            break;
        default:
            dayCount = 31;
            break;
    }
    
    NSMutableArray *dayArray = [NSMutableArray array];
    for (int i=1; i<=dayCount; i++) {
        [dayArray addObject:[NSString stringWithFormat:@"%02d",i]];
    }
    
    _lbDataDict[@(SDL_Day)] = dayArray;
    NSInteger dayIndex = [_lbDataSelectRowDict[@(SDL_Day)] integerValue];
    if (dayIndex >= dayCount) {
        _lbDataSelectRowDict[@(SDL_Day)] = @(dayCount-1);
    }
    return dayCount;
}

- (void)updateYearCount
{
    NSInteger minYear = [_minDateValues[@(SDL_Year)] integerValue];
    NSInteger maxYear = [_maxDateValues[@(SDL_Year)] integerValue];
    
    NSMutableArray *yearArray   = [NSMutableArray array];
    for (NSInteger i=minYear; i<=maxYear; i++) {
        NSString *num = [NSString stringWithFormat:@"%ld",(long)i];
        [yearArray addObject:num];
    }
    _lbDataDict[@(SDL_Year)] = yearArray;

}

#pragma mark - Finish method
- (void)didSelectDate
{
    for (int i = 0; i < _dateLables.count; i++) {
        NSInteger pickerRow = [_myPickerView selectedRowInComponent:i];
        NSInteger selectRow = [_lbDataSelectRowDict[_dateLables[i]] integerValue];
        if (selectRow != pickerRow) {
            [_myPickerView selectRow:selectRow inComponent:i animated:YES];
        }
    }
    
    if (self.didSelectDateBlock) {
        NSMutableArray *values = [NSMutableArray array];
        for (NSNumber *lb in _dateLables) {
            [values addObject:[self valueForLb:[lb integerValue]]];
        }
        
        self.didSelectDateBlock(values);
    }
}

- (void)doDone
{
    [self didSelectDate];
    if (self.doneBlock) {
        self.doneBlock();
    }
}

- (void)doCancel
{
    if (self.cancelBlock) {
        self.cancelBlock();
    }
}


@end
